package cn.fl.collection.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.collection.api.IRskCltAuthApiService;
import cn.fl.collection.api.IRskCltAuthRcdApiService;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.collection.dto.RskCltAuthDTO;
import cn.fl.collection.service.IRskCltAuthRecordService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.risknew.condition.RskCommRecQueryCondition;
import cn.fl.risknew.constant.RiskConstant;
import cn.fl.risknew.dto.RskCommRecDTO;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @Description:    委外催收记录接口实现类
* @Author:         liurong
* @CreateDate:     2020/4/23 14:15
* @Version:        1.0
*/
@Service
public class RskCltAuthRecordServiceImpl implements IRskCltAuthRecordService {

	@Autowired
	private IRskCltAuthApiService rskCltAuthApiService;

	@Autowired
	private IRskCltAuthRcdApiService rskCltAuthRcdApiService;

	@Autowired
	private IUploadApiService uploadApiService;

	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Override
	public DataResultDTO addCltRcd(RskCommRecDTO recordDTO, List<SysUlFilesRecVO> fileList) throws BaseException {
		try {
			if (StringUtils.isEmpty(recordDTO.getBizNo())) {
				throw new BaseException("委外催收ID不能为空！");
			}
			RskCltAuthDTO rskCltAuthDTO = rskCltAuthApiService.selectById(Long.parseLong(recordDTO.getBizNo()));
			if (rskCltAuthDTO == null) {
				throw new BaseException("委外催收数据不存在！");
			}
			recordDTO.setCstId(rskCltAuthDTO.getCstId());
			recordDTO.setCstNm(rskCltAuthDTO.getCstNm());
			recordDTO.setCollectUsrId(CurrentThreadContext.getCurrentUserId());
			recordDTO.setCollectUsrNm(CurrentThreadContext.getCurrentUserName());
			recordDTO.setCollectTm(new Date());
			recordDTO.setDataType(CollectionConstant.CLT_DATA_TYPE);
			recordDTO.setBuTypCd("1");//业务类型（RSK0004）：1.逾期催收
			recordDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			recordDTO.setCrtTm(new Date());
			recordDTO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			recordDTO.setMdfTm(new Date());


			DataResultDTO dataResult = rskCltAuthRcdApiService.addCltRcd(recordDTO);
			if (dataResult != null && dataResult.getSuccess() == BaseConstant.IS_YESNO_YES) {
				Long recordId = Long.valueOf(dataResult.getData().toString());
				try {
					if (CollectionUtils.isNotEmpty(fileList)) {
						// 上传附件
						for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
							sysUlFilesRecVO.setTabNm(CollectionConstant.TAB_NM);
							sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
							sysUlFilesRecVO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
							sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
							sysUlFilesRecVO.setCfgCd(CollectionConstant.CLT_AUTH_FILE_CFG_FLOW);
							sysUlFilesRecVO.setCfgDtlCd(PrjPrdPaySchMConstant.PRJ_PRD_Pay_SCH_M_FILE_DETAIL_CODE);
							sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
							sysUlFilesRecVO.setPkId(String.valueOf(recordId));
							uploadApiService.addSysUlFilesRec(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
						}
					}
					dataResult.setInfo("新增委外催收记录成功！");
				} catch (Exception e) {
					BaseLogUtils.newLogger(recordDTO.getBizNo() + "新增委外催收记录-->附件上传失败！").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0003);
					// 删除
					rskCltAuthRcdApiService.removeById(recordId);

					dataResult.setSuccess(BaseConstant.IS_YESNO_NO);
					dataResult.setInfo("附件上传失败，请稍后重试！");
				}
			}
			return dataResult;
		} catch (BaseException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		}
	}

	@Override
	public Pager searchCltAuthRecordList(Pager page) throws BaseException {
		page = rskCltAuthRcdApiService.searchCltAuthRecordListPage(page);

		List<RskCommRecDTO> resultList = (List<RskCommRecDTO>) page.getResultList();
		translate(resultList);
		return page;
	}

	@Override
	public RskCommRecDTO selectById(Long id) throws BaseException {
		RskCommRecQueryCondition condition = new RskCommRecQueryCondition();
		condition.setId(id);
		condition.setDataType(CollectionConstant.CLT_DATA_TYPE);
		if(CollectionConstant.THIRD_PARTY_COLLECTION_ORG_CD.equals(CurrentThreadContext.getCurrentOrgCd())){
			//当前用户为第三方机构用户
			condition.setCollectUsrId(CurrentThreadContext.getCurrentUserId());
		}
		List<RskCommRecDTO> rskCommRecDTOS = rskCltAuthRcdApiService.searchRskCommRecList(condition);
		if (CollectionUtils.isEmpty(rskCommRecDTOS)) {
			return null;
		}
		translate(rskCommRecDTOS);
		return rskCommRecDTOS.get(0);
	}

	private void translate(List<RskCommRecDTO> list) throws BaseException {
		if (CollectionUtils.isNotEmpty(list)) {
			Map<String, String> cltWayCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_CLT_WAY_CD);
			Map<String, String> debtCauseCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_OVD_REASON_CD);
			for (RskCommRecDTO rskCommRecDTO : list) {
				// 翻译沟通方式RSK0001
				if (StringUtils.isNotEmpty(rskCommRecDTO.getCollectWayCd())) {
					if (cltWayCdMap.containsKey(rskCommRecDTO.getCollectWayCd())) {
						rskCommRecDTO.setCollectWayCdNm(cltWayCdMap.get(rskCommRecDTO.getCollectWayCd()));
					}
				}
				// 翻译欠款原因RSK0011
				if (StringUtils.isNotEmpty(rskCommRecDTO.getOvdReasonCd())) {
					if (debtCauseCdMap.containsKey(rskCommRecDTO.getOvdReasonCd())) {
						rskCommRecDTO.setOvdReasonCdNm(debtCauseCdMap.get(rskCommRecDTO.getOvdReasonCd()));
					}
				}

			}
		}
	}

}
